package com.heima.wemedia.interceptors;

import com.heima.common.threadlocal.UserThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.handler.Handler;

/**
 * @Author RMY
 * @Date 2021/11/26 23:56
 * @Version 1.0
 */
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    //预处理，获得token,解析出userId
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("userId");
        //判断userId是否为空
        if (StringUtils.isNotBlank(userId)){
            //放入threadLocal
            log.info("userId放入了ThreadLocal");
            UserThreadLocalUtils.setUserId(Integer.parseInt(userId));
        }
        return true;
    }


    //处理后
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //用完则清除
        log.info("userId已清除");
        UserThreadLocalUtils.removeUser();
    }
}
